from django.core.paginator import Paginator
from django.db.models import F
from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View

from account.models import MyUser
from album.models import AlbumInfo
from article.models import Comment, ArticleInfo, ArticleTag
from boke.constants import *
from interflow import forms
from .models import Board
from utils.json_res import json_response
from utils.res_code import Code


class Contact(View):
    def get(self,request):
        # 文章
        news_queryset = ArticleInfo.objects.values('id', 'title', 'content', 'articlephoto', 'reading',
                                                   'update_time', ).annotate(
            tag_name=F('article_tag__tag'), author=F('author__username'))
        # 过滤
        news = news_queryset.filter(is_delete=False)
        # 分页
        ArticleList = Paginator(news, PER_PAGE_NEWS_COUNT)
        Articles = ArticleList.page(1)
        # 分类
        tags = ArticleTag.objects.only('id', 'tag').filter(is_delete=False)
        tagList = Paginator(tags, TADGS_PAGE_WALL_COUNT)
        taglists = tagList.page(1)
        # 图片
        albumList = AlbumInfo.objects.all()
        # 进行分页处理
        paginators = Paginator(albumList, ALBUM_PAGE_WALL_COUNT)
        paginator_s = paginators.page(1)
        # 评论
        Comments_page_LIST = Comment.objects.filter(is_delete=False)
        Commentss = Paginator(Comments_page_LIST, COMMENTS_PAGE_WALL_COUNT)
        Comments = Commentss.page(1)
        #管理员
        user=MyUser.objects.filter(id=1).first()
        return render(request,'board.html',locals())
    def post(self,request):
        username=request.session.get('username')
        if username:
            form = forms.BoardForm(request.POST)  # 校验from表单
            # 判定
            if form.is_valid():
                #获取用户id
                id=MyUser.objects.filter(username=username).first().id
                # 获取用户名
                contactname = form.data.get('contactname')
                # 获取邮箱
                email = form.data.get('email')
                # 获取内容
                content = form.data.get('message')
                board=Board(name=contactname,email=email,content=content,user_id=id)
                board.save()
                return json_response(errmsg='提交成功!')
            else:
                # 定义一个错误信息列表
                err_msg_list = []
                for item in form.errors.values():
                    err_msg_list.append(item[0])
                err_msg_str = '/'.join(err_msg_list)

                return json_response(errno=Code.PARAMERR, errmsg=err_msg_str)

        else:
            return json_response(errno=Code.SESSIONERR,errmsg='请登录后进行留言')
